const app = getApp();

Page({
  data: {
    roomNumber: '',
    userId: '',
    currentRound: 0,
    remainingTurns: 0,
    maxSuit: '',
    timer: 30,
    otherPlayers: [],
    playedCards: [],
    myCards: [],
    currentTurn: '',
    isMyTurn: false,
    gameStatus: 'waiting', // waiting, playing, ended
    showPredictionUI: false,
    maxPrediction: 0,  // 本轮最大可预测数
    myPrediction: 0,   // 当前预测值
  },

  onLoad(options) {
    const { roomNumber } = options;
    const userId = wx.getStorageSync('userId');

    this.setData({
      roomNumber,
      userId
    });

    this.initWebSocket();
  },

  initWebSocket() {
    const wsManager = app.globalData.websocketManager;
    
    // 注册消息处理器
    wsManager.registerHandler('game', (data) => {
      this.handleWebSocketMessage(data);
    });

    // 发送加入游戏消息
    wsManager.send({
      phase: 'GAME_PHASE',
      type: 'JOIN_GAME',
      payload: {
        roomNumber: this.data.roomNumber,
        userId: this.data.userId
      }
    });
  },

  handleWebSocketMessage(data) {
    switch (data.type) {
      case 'GAME_STATE':
        this.updateGameState(data.payload);
        // 根据游戏状态显示预测UI
        if (data.payload.status === 'waiting_predictions') {
          const cardsPerPlayer = 2 * (data.payload.currentRound - 1) + 1;
          this.setData({
            showPredictionUI: true,
            maxPrediction: cardsPerPlayer
          });
        } else {
          this.setData({
            showPredictionUI: false
          });
        }
        break;
      case 'DEAL_CARDS':
        this.updateCards(data.payload);
        break;
      case 'TURN_UPDATE':
        this.updateTurn(data.payload);
        break;
      case 'GAME_END':
        this.handleGameEnd(data.payload);
        break;
      case 'PREDICTION_UPDATE':
        this.updatePrediction(data.payload);
        break;
      case 'ROUND_START':
        this.startNewRound(data.payload);
        break;
      case 'ERROR':
        wx.showToast({
          title: data.payload,
          icon: 'none'
        });
        break;
    }
  },

  updateGameState(gameState) {
    this.setData({
      currentRound: gameState.currentRound,
      remainingTurns: gameState.remainingTurns,
      maxSuit: gameState.maxSuit,
      timer: gameState.timer,
      otherPlayers: gameState.players.filter(p => p.id !== this.data.userId),
      playedCards: gameState.playedCards,
      gameStatus: gameState.status
    });
  },

  updateCards(cards) {
    this.setData({
      myCards: cards
    });
  },

  updateTurn(turnData) {
    this.setData({
      currentTurn: turnData.playerId,
      isMyTurn: turnData.playerId === this.data.userId,
      timer: turnData.timer
    });
  },

  handleCardSelect(e) {
    if (!this.data.isMyTurn) return;
    
    const card = e.currentTarget.dataset.card;
    this.ws.send(JSON.stringify({
      phase: 'GAME_PHASE',
      type: 'PLAY_CARD',
      payload: {
        roomNumber: this.data.roomNumber,
        userId: this.data.userId,
        card
      }
    }));
  },

  handleGameEnd(result) {
    // 显示游戏结果
    wx.showModal({
      title: '游戏结束',
      content: `获胜者：${result.winner}`,
      showCancel: false,
      success: () => {
        wx.navigateBack();
      }
    });
  },

  onUnload() {
    // 取消注册消息处理器
    app.globalData.websocketManager.unregisterHandler('game');
  },

  // 新增预测相关方法
  handlePredictionChange(e) {
    const value = parseInt(e.detail.value);
    this.setData({
      myPrediction: value
    });
  },

  submitPrediction() {
    if (this.data.myPrediction < 0 || this.data.myPrediction > this.data.maxPrediction) {
      wx.showToast({
        title: '预测值无效',
        icon: 'none'
      });
      return;
    }

    this.ws.send(JSON.stringify({
      phase: 'GAME_PHASE',
      type: 'MAKE_PREDICTION',
      payload: {
        roomNumber: this.data.roomNumber,
        userId: this.data.userId,
        prediction: this.data.myPrediction
      }
    }));
  }
}); 